import Vue from "vue";
import VueRouter from "vue-router";

import Login from "@/pages/login";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    component: Login
  },
  {
    path: "/welcome",
    meta: {
      requireAuth: true
    },
    component: () => import("@/pages/welcome.vue")
  },
  {
    path: "/functions",
    meta: {
      requireAuth: true
    },
    component: () => import("@/pages/function/index.vue"),
    children: [
      // {
      //   path: "",
      //   component: () => import("@/pages/function/list.vue")
      // },
      // {
      //   path: "add",
      //   component: () => import("@/pages/function/add.vue")
      // },
      {
        path: "",
        component: () => import("@/pages/function/folder.vue")
      }
    ]
  },
  {
    path: "/database",
    meta: {
      requireAuth: true
    },
    component: () => import("@/pages/database/index.vue"),
    children: [
      {
        path: "",
        component: () => import("@/pages/database/list.vue")
      },
      {
        path: "add",
        component: () => import("@/pages/database/add.vue")
      }
    ]
  },
  {
    path: "/reminder",
    meta: {
      requireAuth: true
    },
    component: () => import("@/pages/reminder/index.vue"),
    children: [
      {
        path: "",
        component: () => import("@/pages/reminder/list.vue")
      },
      {
        path: "add",
        component: () => import("@/pages/reminder/add.vue")
      }
    ]
  },
  {
    path: "/docs",
    meta: {
      requireAuth: true
    },
    component: () => import("@/pages/docs/index.vue"),
    children: [
      {
        path: "command",
        component: () => import("@/docs/command.md")
      },
      {
        path: "cloud",
        component: () => import("@/docs/imCloud.md")
      }
    ]
  }
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes
});

router.beforeEach((to, from, next) => {
  if (to.matched[0].meta.requireAuth) {
    // 判断该路由是否需要登录权限
    if (sessionStorage.getItem("token")) {
      // 判断本地是否存在token
      next();
    } else {
      // 未登录,跳转到登陆页面
      next({
        path: "/"
      });
    }
  } else {
    next();
  }
});

export default router;
